import { View, Text, StyleSheet, TextInput, TouchableOpacity, KeyboardAvoidingView, Platform, ScrollView } from 'react-native';
import { useState } from 'react';
import { useRouter } from 'expo-router';
import { communityService } from '../../utils/api/services';
import { MaterialIcons } from '@expo/vector-icons';
import { useAuth } from '../../store/auth/AuthContext';
import Toast from 'react-native-toast-message';

export default function CreateTopicScreen() {
  const router = useRouter();
  const { user } = useAuth();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    if (!title.trim()) {
      Toast.show({
        type: 'error',
        text1: '请输入标题',
      });
      return;
    }

    if (!content.trim()) {
      Toast.show({
        type: 'error',
        text1: '请输入内容',
      });
      return;
    }

    if (!user?.id) {
      Toast.show({
        type: 'error',
        text1: '用户未登录',
        text2: '请先登录后再发布话题',
      });
      router.replace('/user/login');
      return;
    }

    try {
      setSubmitting(true);
      await communityService.createTopic({
        user_id: Number(user.id),
        title: title.trim(),
        content: content.trim(),
      });
      
      Toast.show({
        type: 'success',
        text1: '发布成功',
      });
      
      router.back();
    } catch (error) {
      console.error('发布话题失败:', error);
      Toast.show({
        type: 'error',
        text1: '发布失败',
        text2: '请稍后重试',
      });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <KeyboardAvoidingView 
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton}>
          <MaterialIcons name="arrow-back" size={24} color="#333" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>发布话题</Text>
        <View style={styles.headerRight} />
      </View>

      <ScrollView style={styles.content}>
        <TextInput
          style={styles.titleInput}
          placeholder="请输入标题（必填）"
          placeholderTextColor="#999"
          value={title}
          onChangeText={setTitle}
          maxLength={50}
        />
        <View style={styles.divider} />
        <TextInput
          style={styles.contentInput}
          placeholder="请输入内容（必填）&#10;分享你的想法..."
          placeholderTextColor="#999"
          value={content}
          onChangeText={setContent}
          multiline
          textAlignVertical="top"
        />
      </ScrollView>

      <View style={styles.footer}>
        <TouchableOpacity
          style={[styles.submitButton, (!title.trim() || !content.trim() || submitting) && styles.submitButtonDisabled]}
          onPress={handleSubmit}
          disabled={!title.trim() || !content.trim() || submitting}
        >
          <Text style={styles.submitButtonText}>
            {submitting ? '发布中...' : '发布话题'}
          </Text>
        </TouchableOpacity>
      </View>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    backgroundColor: '#fff',
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#333',
  },
  headerRight: {
    width: 32,
  },
  content: {
    flex: 1,
  },
  titleInput: {
    fontSize: 20,
    fontWeight: '500',
    padding: 16,
    color: '#333',
  },
  divider: {
    height: 1,
    backgroundColor: '#eee',
    marginHorizontal: 16,
  },
  contentInput: {
    flex: 1,
    fontSize: 16,
    lineHeight: 24,
    padding: 16,
    color: '#333',
    minHeight: 200,
  },
  footer: {
    padding: 16,
    borderTopWidth: 1,
    borderTopColor: '#eee',
    backgroundColor: '#fff',
  },
  submitButton: {
    backgroundColor: '#007AFF',
    padding: 16,
    borderRadius: 8,
    alignItems: 'center',
  },
  submitButtonDisabled: {
    backgroundColor: '#ccc',
  },
  submitButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: '500',
  },
}); 